package chuangyi.com.org.DOMIHome;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

/**
 * Created by zxh on 16/12/15.
 */

public class NestedEditText extends EditText {

    private View.OnTouchListener touchListener = null;

    private View.OnTouchListener mTouchListener = new OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (view instanceof  EditText && canVerticalScroll()) {
                view.getParent().requestDisallowInterceptTouchEvent(true);
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    view.getParent().requestDisallowInterceptTouchEvent(false);
                }
            }
            if(touchListener != null){
                touchListener.onTouch(view, motionEvent);
            }
            return false;
        }
    };

    public NestedEditText(Context context){
        super(context);
        super.setOnTouchListener(mTouchListener);
    }

    public NestedEditText(Context context, AttributeSet attrs){
        super(context, attrs);
        super.setOnTouchListener(mTouchListener);
    }

    public NestedEditText(Context context, AttributeSet attrs, int defStyleAttr){
        super(context, attrs, defStyleAttr);
        super.setOnTouchListener(mTouchListener);
    }

    /**
     * EditText竖直方向是否可以滚动
     * @param editText 需要判断的EditText
     * @return true：可以滚动  false：不可以滚动
     */
    private boolean canVerticalScroll() {
        //滚动的距离
        int scrollY = this.getScrollY();
        //控件内容的总高度
        int scrollRange = this.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = this.getHeight() - this.getCompoundPaddingTop() -this.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    @Override public void setOnTouchListener(View.OnTouchListener listener){
        touchListener = listener;
    }
}
